//
//  JZNRequestUtil.m
//  taishan
//
//  Created by mac on 2019/4/8.
//  Copyright © 2019年 jznrj. All rights reserved.
//

#import "JZNRequestUtil.h"
#import <MJExtension.h>
@implementation JZNRequestUtil
+(void) requestUrl: (NSString*) urlString
     requestParams: (NSDictionary*)params
           success: (void(^)(DataResult *dataResult)) success
           failure: (void(^)(NSError *error)) failure{
    
    NSURL *url = [NSURL URLWithString: urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
    [request setHTTPMethod: @"POST"];
    if (params) {
        if (![request valueForHTTPHeaderField:@"Content-Type"]) {
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        }
        [request setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] forHTTPHeaderField:@"token"];
        [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil]];
    }
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask =
    [session dataTaskWithRequest:request
               completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                   if (error) {
                       failure(error);
                   } else {
                       NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                       dispatch_async(dispatch_get_main_queue(), ^{
                           DataResult *dataResult = [DataResult mj_objectWithKeyValues:responseString];
                           success(dataResult);
                           
                       });
                       
                   }
               }];
    [dataTask resume];
    
}
@end
